from re import search

from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.system.user import user_controller
from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.settings import settings
from app.controllers.orders.goods import orders_goods_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.marketing import *
from app.models.customer import CustomerUser
from app.models.goods import Goods
from app.models.marketing import Commission
from app.controllers.marketing.commission import commission_controller
from app.controllers.customer.users import users_controller
from app.controllers.customer.grow import growController

commission_router = APIRouter()
model_name = "佣金发放"


@commission_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"用户姓名"),
        goods_name: str = Query(None, description=f"商品名称"),
):
    search_user_ids = []
    search_goods_ids = []

    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    if goods_name:
        search_goods = await Goods.filter(name__contains=goods_name).values("id")
        search_goods_ids = {orders['id'] for orders in search_goods}  # 获取所有的 user_id
    q = Q(status=1)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if goods_name:
        q &= Q(goods_id__in=search_goods_ids)
    total, data = await orders_goods_controller.do_list(page=page, page_size=page_size, search=q)

    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    goods_ids = {orders['goods_id'] for orders in data}  # 获取所有的 goods_id
    ids = {orders['id'] for orders in data}  # 获取所有的 goods的id,查询收益表记录

    users = await CustomerUser.filter(id__in=user_ids)
    goods = await Goods.filter(id__in=goods_ids)
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    q1 = Q(orders_goods_id__in=ids)
    if user.space_id:
        q1 &= Q(space_id=user.space_id)
    commissions = await Commission.filter(q1)

    users_dict = {user.id: user.name for user in users}
    goods_dict2 = {good.id: good.cover for good in goods}
    goods_dict = {good.id: good.name for good in goods}
    commission_dict = {commission.orders_goods_id: commission.id for commission in commissions}

    for car in data:
        car['user_name'] = users_dict.get(car['user_id'], "已删除用户")
        car['goods_name'] = goods_dict.get(car['goods_id'], "已删除商品")
        car['goods_cover'] = goods_dict2.get(car['goods_id'], "")
        status = commission_dict.get(car['id'], 0)
        if status>0:
            car['status_name'] = "已发放"
        else:
            car['status_name'] = "未发放"

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@commission_router.post("/update", summary="发放佣金")
async def do_status(
        data:CommissionStatus
):
    await commission_controller.do_status(data_id=data.data_id,status=data.status)
    return Success(msg="操作成功")

@commission_router.post("/update_mx", summary=f"更新{model_name}")
async def do_update_mx(
        data_in: CommissionUpdate,
):
    await commission_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@commission_router.get("/income", summary=f"查看{model_name}明细记录列表")
async def do_income(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"用户姓名"),
        goods_name: str = Query(None, description=f"商品名称"),
):
    search_user_ids = []
    search_goods_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    if goods_name:
        search_goods = await Goods.filter(name__contains=goods_name).values("id")
        search_goods_ids = {orders['id'] for orders in search_goods}  # 获取所有的 user_id
    q = Q(status=0)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if goods_name:
        q &= Q(goods_id__in=search_goods_ids)
    total, data = await commission_controller.do_list(page=page, page_size=page_size, search=q)

    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    goods_ids = {orders['goods_id'] for orders in data}  # 获取所有的 goods_id
    level_objs = await users_controller.level_list()
    grow_objs = await growController.level_list()


    users = await CustomerUser.filter(id__in=user_ids)
    goods = await Goods.filter(id__in=goods_ids)


    users_dict = {user.id: user.name for user in users}
    goods_dict = {good.id: good.name for good in goods}

    for car in data:
        car['user_name'] = users_dict.get(car['user_id'], "已删除用户")
        car['goods_name'] = goods_dict.get(car['goods_id'], "已删除商品")
        car["user_level_name"] = level_objs[car["user_level"]]
        car["grow_id_name"] = grow_objs[car["grow_id"]]


    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)